package com.ndood.polling.app.properties;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;

import lombok.extern.slf4j.Slf4j;

/**
 * 从数据库加载配置信息到容器
 * https://www.jianshu.com/p/558e51439e07
 * @author ndood
 */
@Configuration("dbGlobalConfig")
@Slf4j
public class DBGlobalConfig {
	
	@Autowired
	private PollingProperties pollingProperties;
	
	@Autowired
    private ConfigurableEnvironment environment;

    @PostConstruct
    public void initDatabasePropertySourceUsage() {
        // 获取系统属性集合
        MutablePropertySources propertySources = environment.getPropertySources();

        try {
            // 从数据库获取自定义变量列表
            Map<String, String> dbConfigMap = new HashMap<>();
            // TODO 从数据库读取全局配置信息到map
            dbConfigMap.put("ndood.polling.global-config.app-id", "1111");
            dbConfigMap.put("ndood.polling.global-config.mch-id", "2222");
            dbConfigMap.put("ndood.polling.global-config.key", "3333");
            dbConfigMap.put("ndood.polling.global-config.cert-stream", "4444");
            dbConfigMap.put("ndood.polling.global-config.url", "5555");
            
            // 将转换后的列表加入属性中
            Properties properties = new Properties();
            properties.putAll(dbConfigMap);

            // 将属性转换为属性集合，并指定名称
            PropertiesPropertySource dbPropertySource = new PropertiesPropertySource("dbGlobalConfig", properties);

            // 如果使用数据库配置，则覆盖系统默认配置
            if(pollingProperties.getIsDbGlobalConfig()) {
            	propertySources.addFirst(dbPropertySource);
            }
            
        } catch (Exception e) {
        	
        	log.error("从数据库加载配置信息失败！",e);
            throw new RuntimeException(e);
        
        }
    }

}
